﻿using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Scripting;
using Microsoft.Scripting.Ast;
using Microsoft.Linq.Expressions;

namespace DlrBasic.Parser.Ast
{
    class If : Statement
    {
        DlrBasicExpression test;
        Statement[] thenBranch;
        Statement[] elseBranch;

        public If(SourceSpan span, DlrBasicExpression test, Statement[] thenBranch, Statement[] elseBranch)
            : base(span)
        {
            this.test = test;
            this.thenBranch = thenBranch;
            this.elseBranch = elseBranch;
        }

        public override void Visit(StatementsVisitor visitor)
        {
            base.Visit(visitor);

            visitor.IfThen(this);
            if (thenBranch != null)
            {
                foreach (Statement statement in thenBranch)
                {
                    statement.Visit(visitor);
                }
            }
            visitor.IfElse(this);
            if (elseBranch != null)
            {
                foreach (Statement statement in elseBranch)
                {
                    statement.Visit(visitor);
                }
            }
            visitor.IfEnd(this);
        }

        protected internal override Expression Generate(DlrBasicGenerator generator, StateMemberGenerator stateParameter, LambdaBuilder builder)
        {
            Expression thenExpression;
            thenExpression = Utils.Assign(
                stateParameter.GetCurrentStatementVariable(), 
                Utils.Constant(generator.GetStatementNumber(thenBranch[0])),
                thenBranch[0].SourceSpan);

            Expression elseExpression;
            if(elseBranch == null)
            {
                elseExpression = base.Generate(generator, stateParameter, builder);
            }
            else
            {
                elseExpression = Utils.Assign(
                    stateParameter.GetCurrentStatementVariable(), 
                    Utils.Constant(generator.GetStatementNumber(elseBranch[0])),
                    elseBranch[0].SourceSpan);
            }

            Expression testExpression = TypeConversionUtils.BuildTestIfTrue(
                 test.Generate(generator));

            return Utils.Condition(testExpression,
                thenExpression, elseExpression, SourceSpan);
        }
    }
}
